package log

import (
	"fmt"
	"strings"
	"sync"
	"time"
)

var (
	DefaultLogConfig = &LogConfig{
		LogChanCap:       1000,
		LogFileName:      "log",
		LogWriteInterval: 1, // 1s
	}

	pkgVarLogConfig       *LogConfig
	pkgVarLogConfigOnce   sync.Once
	pkgVarLogInstance     *LogInstance
	pkgVarLogInstanceOnce sync.Once
)

func Log(a ...any) {
	logChan := getLogInstance().logChan
	now := time.Now()
	logContentBuf := &strings.Builder{}
	for argNum, arg := range a {
		if argNum > 0 {
			logContentBuf.WriteString(" ")
		}
		logContentBuf.WriteString(fmt.Sprintf("%v", arg))
	}
	logContent := logContentBuf.String()
	logChan <- LogLine{
		LogContent: &logContent,
		LogTime:    &now,
	}
}

func Logf(format string, a ...any) {
	logChan := getLogInstance().logChan
	now := time.Now()
	logContent := fmt.Sprintf(format, a...)
	logChan <- LogLine{
		LogContent: &logContent,
		LogTime:    &now,
	}
}

func getLogInstance() *LogInstance {
	pkgVarLogInstanceOnce.Do(func() { // 单例 pkgVarLogInstance
		pkgVarLogInstance = NewLogInstance()
		pkgVarLogInstance.logMain()
	})
	return pkgVarLogInstance
}

// InitLog可省略，省略后使用默认配置
func InitLog(c *LogConfig) { // 单例 pkgVarLogConfig
	if c == nil {
		return
	}
	pkgVarLogConfigOnce.Do(func() {
		if c.LogChanCap == 0 {
			c.LogChanCap = DefaultLogConfig.LogChanCap
		}
		if c.LogFileName == "" {
			c.LogFileName = DefaultLogConfig.LogFileName
		}
		if c.LogWriteInterval == 0 {
			c.LogWriteInterval = DefaultLogConfig.LogWriteInterval
		}
		pkgVarLogConfig = c
	})
}

func CloseLog() {
	if pkgVarLogInstance != nil {
		pkgVarLogInstance.logClose()
	}
}
